#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import sys
import os
import argparse
import subprocess
import stat


def create_python_module(m):
    """
    create python module with name 'm'
    :param m:
    :return:
    """
    module_path = os.path.join(os.getcwd(), m)
    if not os.path.exists(module_path):
        os.makedirs(module_path)
    with open(os.path.join(module_path, '__init__.py'), 'w'):
        pass


def create_shell_scripts():
    """
    创建快速启动的shell脚本
    :return:
    """
    bin_path = os.path.join(os.getcwd(), 'bin')
    if not os.path.exists(bin_path):
        os.makedirs(bin_path)
    run_sh_path = os.path.join(bin_path, 'run.sh')
    with open(run_sh_path, 'w') as f:
        f.write('''#!/usr/bin/env bash

source .venv/bin/activate
python ljwmt/main.py "$@"
''')
    # add exec permission for sh file
    st = os.stat(run_sh_path)
    os.chmod(run_sh_path, st.st_mode | stat.S_IEXEC)
    with open(os.path.join(bin_path, 'run.bat'), 'w') as f:
        f.write('''@echo off
call .venv/Scripts/activate.bat
python ljwmt/main.py %*
''')


def create_git_ignore():
    """
    create .gitignore
    """
    with open(os.path.join(os.getcwd(), '.gitignore'), 'w') as f:
        n = f.write('''.venv
.DS_Store
.cache
Pipfile.lock
__pycache__/
report/

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
''')
    pass


def create_editor_config():
    """
    create .editorconfig
    """
    with open(os.path.join(os.getcwd(), '.editorconfig'), 'w') as f:
        n = f.write('''root = true

[*]
charset = utf-8
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
''')
    pass


def create_read_me(project):
    """
    create README.md
    """
    with open(os.path.join(os.getcwd(), 'README.md'), 'w') as f:
        n = f.write('\n### {} 自动化测试'.format(project))
    pass


def custom_env(args):
    my_env = os.environ.copy()
    if "PIPENV_VENV_IN_PROJECT" not in my_env:
        if args.verbose:
            print('make sure venv is set in project with pipenv')
        my_env['PIPENV_VENV_IN_PROJECT'] = 'true'
    return my_env


def set_pip_env(args):
    """
    设置 PIPENV 环境
    """
    print("call pipenv to init dev env ...")
    pipenv_args = [args.pipenv]
    if args.python is None:
        pipenv_args += ['--three']
    else:
        pipenv_args += ['--python=' + args.python]
    if args.verbose:
        print("Run subprocess with args {} in env {}".format(pipenv_args, custom_env(args)))
    p = subprocess.Popen(pipenv_args, env=custom_env(args))
    p.wait()


def install_libs(args):
    """
    安装必要的依赖包
    :param args:
    :return:
    """
    pipenv_args = [args.pipenv]
    libs = ['requests',
            'pytest',
            'beautifulsoup4',
            'pymysql',
            'pytest-html']
    p = subprocess.Popen(pipenv_args + ['install'] + libs, env=custom_env(args))
    p.wait()


def main():
    parser = argparse.ArgumentParser(description='The init tool for ljwmt')
    parser.add_argument("project-name", type=str, help='the project name to be tested')
    parser.add_argument("-v", "--verbose", dest='verbose', action='store_true',
                        help="increase output verbosity to track issue")
    parser.add_argument("--pipenv", default="pipenv",
                        help="the full path of pipenv execute file, default: pipenv")
    parser.add_argument("--python",
                        help='the full path of python execute file, if set, init project with "pipenv --python=PYTHON",'
                             ' default use "pipenv --three"')
    args = parser.parse_args()
    if args.verbose:
        print("Run tool in {} with args: {}".format(os.getcwd(), args))
    project = getattr(args, 'project-name')
    print("Init automation test for {} ...".format(project))
    create_read_me(project)
    create_editor_config()
    create_git_ignore()
    for m in ["api", "case", "warmup", "cleanup", project]:
        create_python_module(m)
    if not os.path.exists(os.path.join(os.getcwd(), '.venv')):
        set_pip_env(args)
    install_libs(args)
    create_shell_scripts()
    print("Done!")
    return 0

if __name__ == '__main__':
    sys.exit(main())
